import 'dart:math';

import 'package:flutter/material.dart';

class PracticePage extends StatefulWidget {
  const PracticePage({super.key});

  @override
  State<PracticePage> createState() => _PracticePageState();
}

class _PracticePageState extends State<PracticePage> {
  final List<String> _questions = [];
  final List<String> _userAnswers = [];
  final List<int> _results = [];
  int _correctCount = 0;
  int _totalQuestions = 0;
  int _incorrectCount = 0;
  String _selectedType = 'Addition';
  int _questionCount = 10;

  final Map<String, Function> _operations = {
    'Addition': (int a, int b) => a + b,
    'Subtraction': (int a, int b) => a - b,
    'Multiplication': (int a, int b) => a * b,
    'Division': (int a, int b) => a ~/ b,
  };

  void _generateQuestions() {
    final random = Random();
    setState(() {
      _questions.clear();
      _userAnswers.clear();
      _results.clear();
      _correctCount = 0;
      _incorrectCount = 0;
      _totalQuestions = _questionCount;

      for (int i = 0; i < _questionCount; i++) {
        final int a = random.nextInt(50) + 1;
        final int b = random.nextInt(49) + 1;
        String operation = _selectedType;

        if (_selectedType == 'Mixed') {
          operation = _operations.keys.elementAt(random.nextInt(4));
        }

        final result = _operations[operation]!(a, b);
        _results.add(result);

        if (operation == 'Division') {
          _questions.add('$a ÷ $b');
        } else if (operation == 'Multiplication') {
          _questions.add('$a × $b');
        } else if (operation == 'Subtraction') {
          _questions.add('$a - $b');
        } else {
          _questions.add('$a + $b');
        }

        _userAnswers.add('');
      }
    });
  }

  void _submitAnswers() {
    setState(() {
      _correctCount = 0;
      _incorrectCount = 0;
      for (int i = 0; i < _questions.length; i++) {
        if (_userAnswers[i] == _results[i].toString()) {
          _correctCount++;
        } else {
          _incorrectCount++;
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Math Quiz Practice'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            DropdownButton<String>(
              value: _selectedType,
              onChanged: (String? newValue) {
                setState(() {
                  _selectedType = newValue!;
                });
              },
              items: <String>['Addition', 'Subtraction', 'Multiplication', 'Division', 'Mixed']
                  .map<DropdownMenuItem<String>>((String value) {
                return DropdownMenuItem<String>(
                  value: value,
                  child: Text(value),
                );
              }).toList(),
            ),
            Row(
              children: [
                const Text('Number of questions: '),
                DropdownButton<int>(
                  value: _questionCount,
                  onChanged: (int? newValue) {
                    setState(() {
                      _questionCount = newValue!;
                    });
                  },
                  items: [5, 10, 15, 20]
                      .map<DropdownMenuItem<int>>((int value) {
                    return DropdownMenuItem<int>(
                      value: value,
                      child: Text(value.toString()),
                    );
                  }).toList(),
                ),
              ],
            ),
            ElevatedButton(
              onPressed: _generateQuestions,
              child: const Text('Generate Questions'),
            ),
            Expanded(
              child: ListView.builder(
                itemCount: _questions.length,
                itemBuilder: (context, index) {
                  return Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            '${index + 1}. ${_questions[index]} = ',
                            style: const TextStyle(fontSize: 16),
                          ),
                        ),
                        SizedBox(
                          width: 80,
                          child: TextField(
                            keyboardType: TextInputType.number,
                            onChanged: (value) {
                              _userAnswers[index] = value;
                            },
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ),
            ElevatedButton(
              onPressed: _submitAnswers,
              child: const Text('Submit'),
            ),
            const SizedBox(height: 16),
            Text('Total Questions: $_totalQuestions'),
            Text('Correct Answers: $_correctCount'),
            Text('Incorrect Answers: $_incorrectCount'),
          ],
        ),
      ),
    );
  }
}
